// src\views\sendbox\home\Home.jsx
// 首页
import React, { useEffect, useState, useRef } from 'react'
import { Avatar, Card, Col, Drawer, List, Row } from 'antd';
import axios from 'axios';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import _ from 'lodash'//js实用工具库
import * as Echarts from 'echarts'


const { Meta } = Card;

export default function Home() {
  const [viewList, setviewList] = useState([]);
  const [starList, setstarList] = useState([]);
  const [allList, setallList] = useState([])
  const [visible, setvisible] = useState(false);
  const [pieChart, setpieChart] = useState(null)
  const pieRef = useRef();
  const barRef = useRef();


  const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    axios.get('http://localhost:8888/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6').then(res => {
      setviewList(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get('http://localhost:8888/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6').then(res => {
      setstarList(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get("http://localhost:8888/news?publishState=2&_expand=category").then(res => {
      console.log("allList", res.data);
      renderBarView(_.groupBy(res.data, item => item.category.title));
      setallList(res.data);
    })
  }, []);
  const renderBarView = (obj) => {
    var myChart = Echarts.init(barRef.current);
    //指定图表的配置项和数据
    var option = {
      title: {
        text: "新闻分类图示"
      },
      tooltip: {},
      legend: {
        data: ['数量']
      },
      xAxis: {
        data: Object.keys(obj),//取出所有的key值
        axiosLabel: {
          rotate: '45',
          interval: 0
        }
      },
      yAxis: {
        minInterval: 1
      },
      series: [{
        name: "数量",
        type: 'bar',
        data: Object.values(obj).map(item => item.length)
      }]

    }
    // 配置
    myChart.setOption(option);

    window.onreset = () => {
      myChart.resize();
    }
  }
  // 初始化
  const renderPieview = () => {

    var currentList = allList.filter(item => item.author === username);
    var groupObj = _.groupBy(currentList, item => item.category.title);
    // console.log(groupObj);

    var list = [];
    for (var i in groupObj) {
      list.push({
        name: i,
        value: groupObj[i].length
      })
    }
    // console.log(list);
    console.log("饼图初始化", pieRef.current);

    var myChart;
    if(!pieChart){
      myChart = Echarts.init(pieRef.current);
      setpieChart(myChart);
    }else{
      myChart=pieChart;
    }
    var option;
     option = {
      title: {
        text: "当前用户新闻分类图示",
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: "vertical",
        left: 'left'
      },
      series: [
        {
          name: '发布数量',
          type: "pie",
          radius: '50%',
          data: list,
          emphasis: {
            itemStyle:{
              shadowBlur:10,
              shadowOffsetX:0,
              shadowColor:'rgba(0,0,0,0.5)'
            }
          }
        }
      ]
    };
    option&&myChart.setOption(option);
    window.onresize = () => {
      // console.log("resize")
      myChart.resize()
  }
  }
  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col className="gutter-row" span={8}>
          <Card title='用户最常浏览' bordered={true}>
            <List size='small'
              dataSource={viewList}
              renderItem={item => <List.Item>
                <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
              </List.Item>}></List>
          </Card>
        </Col>
        <Col className="gutter-row" span={8}>
          <Card title='用户点赞最多' bordered={true}>
            <List size='small'
              dataSource={starList}
              renderItem={item => <List.Item>
                <a href={`#/news-manage/preview/${item.id}`}>{item.title}</a>
              </List.Item>}>
            </List>
          </Card>
        </Col>
        <Col className="gutter-row" span={8}>
          <Card cover={
            <img alt='example'
              src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
            />
          }
            actions={[
              <SettingOutlined key='setting' onClick={() => {
                setTimeout(() => {
                  setvisible(true);
                  //init初始化
                  renderPieview()
                }, 0);
              }} />,
              <EditOutlined key='edit' />,
              <EllipsisOutlined key='ellipsis' />
            ]}
          ></Card>
          <Meta
            avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
            title={username}
            description={
              <div>
                <b>{region ? region : "全球"}</b>
                <span style={{
                  paddingLeft: '30px'
                }}>{roleName}</span>
              </div>
            }
          ></Meta>
        </Col>
      </Row>
      {/* 抽屉 */}
      <Drawer
        width='500px'
        title='个人新闻分类'
        placement='right'
        open={visible}
        onClose={() => {
          setvisible(false);
        }}
      >
        {/* 饼图 */}
        <div ref={pieRef} style={{
          width: '100%',
          height: '100%',
          marginTop: '30px'
        }}></div>
      </Drawer>
      {/* 柱状图 */}
      <div ref={barRef} style={{
        width: '100%',
        height: '400px',
        marginTop: '30px'
      }}></div>
    </div>
  )
}
